package com.huifaapp.mall.selectImage;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huifaapp.mall.APP;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.BaseActivity;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ChooseImageActivity extends BaseActivity {
    private static final String TAG = "ChooseImageActivity";

    public static final String INTENT_PARAMETER_ISOPERATE = "isOperate";
    public static final String INTENT_PARAMETER_IMAGECOUNT = "ImageCount";
    public static final String INTENT_PARAMETER_RETURNCLASS = "ReturnClass";
    /**图片的大小要求，单位：byt*/
    public static final String EXTRA_LIMIT_SIZE = "LIMIT_SIZE";
    /**是否需要创建缩略图*/
    public static final String EXTRA_NEED_TH = "NEED_TH";

    public static final int REQCODE_TRIM = 1;
    public static final int RESCODE_BITMAPBYTE = 1;
    public static final int RESCODE_BITMAPPATHS = 2;// 返回到IM頁面并返回選擇餓圖片的路徑的resultCode值
    public static final int REQCODE_PHOTOALBUM = 2;// 跳转到PhotoalbumActivity（相册列表）的requestCode值
    public static final int REQCODE_PHOTOALBUM_CLOSE = 3;// 跳转到PhotoalbumActivity（相册列表）的requestCode值

    public static final int MESSAGE_WHAT_SHENDIMAGE = 1;
    public static final int MESSAGE_WHAT_ERROR = -1;

    Button btn_choose_preview;
    Button btn_choose_send;
    TextView tv_choose_trim;// 裁剪
    TextView tv_choose_imagestandard;// 图片大小标准
    PhotoGridView gridView;
    RelativeLayout BottomLayout;
    RelativeLayout rlNoData;
    PopupWindow PopuImagestandardMenu;

    ChooseImageAdapter adapter;

    List<String> paths;
    ArrayList<String> AllPath;
    Map<String, String> Choosemap;
    LruCache<String, Bitmap> map;
    ArrayList<Pair<String, String>> ResPahts;

    int ScreenWeight;// 屏幕宽度
    int ImageCountMax;

    boolean isOperate;

    WindowManager windowManager;
    ExecutorService executorServic;

    /**文件的限制大小，单位：MB，默认不限制*/
    private float mLimitSize = -1;
    /**是否需要创建缩略图，默认不创建*/
    private boolean isNeedTh = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        initIntent();
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_chooseimage;
    }

    @Override
    protected void initialize() {

    }

    @Override
    protected void initView() {

    }

    public void init() {
        gridView = (PhotoGridView) findViewById(R.id.imageGallery);
        tv_choose_trim = (TextView) findViewById(R.id.tv_choose_trim);
        tv_choose_imagestandard = (TextView) findViewById(R.id.tv_choose_imagestandard);
        btn_choose_preview = (Button) findViewById(R.id.btn_choose_preview);
        btn_choose_send = (Button) findViewById(R.id.btn_choose_send);
        BottomLayout = (RelativeLayout) findViewById(R.id.rlChooseimageBottom);
        rlNoData = (RelativeLayout) findViewById(R.id.rlNoData);
        ObtainSystemImage getImage = new ObtainSystemImage();
        AllPath = (ArrayList<String>) getImage.getimage(this);
        if (AllPath == null || AllPath.size() == 0)
            rlNoData.setVisibility(View.VISIBLE);
        paths = AllPath;
        adapter = new ChooseImageAdapter();
        gridView.setiLoadingImage(new LoadingImage());
        gridView.setAdapter(adapter);
        gridView.setFocusable(false);
        gridView.setFocusableInTouchMode(false);
        executorServic = Executors.newFixedThreadPool(5);
        ImageCountMax = 5;
        isOperate = true;
        map = ((APP) getApplication()).map;
        Choosemap = new HashMap<String, String>();
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        ScreenWeight = windowManager.getDefaultDisplay().getWidth();
    }

    public void initIntent() {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        Bundle bundle = intent.getExtras();
        if (bundle == null) {
            return;
        }
        //选择图片的大小限制
        long limit = bundle.getLong(EXTRA_LIMIT_SIZE, -1);
        if(limit != -1){
            mLimitSize = (float)limit / 1024 / 1024;
        }
        //选择图片的数量限制
        ImageCountMax = bundle.getInt(INTENT_PARAMETER_IMAGECOUNT);
        //是否可以对选取的图片做裁剪，预览的操作
        isOperate = bundle.getBoolean(INTENT_PARAMETER_ISOPERATE, true);
        if (!isOperate) {
            BottomLayout.setVisibility(View.GONE);
        }
        //是否需要创建缩略图
        isNeedTh = bundle.getBoolean(EXTRA_NEED_TH, false);
    }

    public void onAction(View v) {
        switch (v.getId()) {
            case R.id.ibChoose_back:
                if (paths == null || paths.size() == 0) {
                    finish();
                    return;
                }
                Intent Photoalbumintent = new Intent(this, PhotoalbumActivity.class);
                Bundle Photoalbumbundle = new Bundle();
                Photoalbumbundle.putStringArrayList("paths", AllPath);
                Photoalbumintent.putExtras(Photoalbumbundle);
                startActivityForResult(Photoalbumintent, REQCODE_PHOTOALBUM);
                break;
            case R.id.btn_choose_preview:
                if (Choosemap.size() == 0) {
                    showMsg("请至少选择一张照片");
                } else {
                    ArrayList<String> files = new ArrayList<>();
                    for (String string : Choosemap.keySet()) {
                        files.add(string);
                    }
                    Intent intent = new Intent(ChooseImageActivity.this, ImageGalleryActivity.class);
                    intent.putStringArrayListExtra(ImageGalleryActivity.EXTRA_IMAGES, files);
                    startActivity(intent);
                }
                break;
            case R.id.btn_choose_send:
                new ImageCompressionThread(Choosemap, RootFile.getCacheFiles().getAbsolutePath()).start();
                btn_choose_send.setClickable(false);
                break;
            case R.id.tv_choose_trim:
                if (Choosemap.size() == 1) {
                    for (String path : Choosemap.keySet()) {
                        Intent intent = new Intent(this, CropImageActivity.class);
                        intent.putExtra("path", path);
                        intent.putExtra("IsUpload", false);
                        intent.putExtra("maintainAspectRatio", false);
                        startActivityForResult(intent, 1);
                        break;
                    }
                }
                break;
            case R.id.tv_choose_imagestandard:
                if (Choosemap.size() == 0) {
                    break;
                }
                break;
            case R.id.actionChoose:
                finish();
                break;
        }
    }

    @SuppressLint("NewApi") @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQCODE_TRIM:
                if (resultCode == CropImageActivity.RESCODE_PATH) {
                    String path = data.getStringExtra("path");
                    Choosemap = new HashMap<String, String>();
                    Choosemap.put(path, path);
                    new ImageCompressionThread(Choosemap, RootFile.getCacheFiles().getAbsolutePath()).start();
                    btn_choose_send.setClickable(false);
                    return;
                }
                break;
            case REQCODE_PHOTOALBUM:
                if (resultCode == PhotoalbumActivity.RESCODE_STRING) {
                    if (data == null)
                        return;
                    Bundle bundle = data.getExtras();
                    if (bundle == null)
                        return;
                    paths = bundle.getStringArrayList("paths");
                    adapter.notifyDataSetInvalidated();
                }else{
                    finish();
                }
                break;
        }
    }

    class ChooseImageAdapter extends BaseAdapter {
        int firstVisibleItem = 0;
        int visibleItemCount = 18;

        @Override
        public int getCount() {
            if (paths == null)
                return 0;
            return paths.size();
        }

        @Override
        public Object getItem(int arg0) {
            return paths.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @SuppressLint("NewApi")
        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            if (arg1 == null) {
                arg1 = LayoutInflater.from(ChooseImageActivity.this).inflate(R.layout.item_chooseimage_imagegridview, null);
            }
            ImageView imageView = (ImageView) arg1.findViewById(R.id.Imagegridviewitem);
            LayoutParams layoutParams = (LayoutParams) imageView.getLayoutParams();
            layoutParams.width = (int) (ScreenWeight / 3 - BitmapCondense.DIPtoPX(ChooseImageActivity.this, 4));
            layoutParams.height = (int) (ScreenWeight / 3 - BitmapCondense.DIPtoPX(ChooseImageActivity.this, 4));
            final ImageView ImagegridviewitemChoose = (ImageView) arg1.findViewById(R.id.ImagegridviewitemChoose);
            if (Choosemap.get(paths.get(arg0)) != null) {
                ImagegridviewitemChoose.setVisibility(View.VISIBLE);
            } else {
                ImagegridviewitemChoose.setVisibility(View.GONE);
            }
            imageView.setTag(paths.get(arg0));
            if (map.get(paths.get(arg0)) != null && map.get(paths.get(arg0)) != null) {
                imageView.setImageBitmap(map.get(paths.get(arg0)));
            } else {
                imageView.setImageResource(R.drawable.icon_empty);
                if (arg0 >= adapter.firstVisibleItem && arg0 <= adapter.firstVisibleItem + adapter.visibleItemCount) {
                    int height = ScreenWeight / 7;
                    int width = ScreenWeight / 7;
                    height = height < 100 ? 100 : height;
                    width = width < 100 ? 100 : width;
                    height = height < 200 ? height : 200;
                    width = width < 200 ? width : 200;
                    LocalImageThread imageThread = new LocalImageThread(paths.get(arg0), width, height, imageView);
                    imageThread.setLruCache(map);
                    imageThread.setIlocalImageAsyncTask(asyncTask);
                    executorServic.execute(imageThread);
                }
            }
            View.OnClickListener onClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getTag() == null) {
                        return;
                    }
                    String key = (String) v.getTag();
                    Bitmap bt = BitmapCondense.Condense(10, 10, key);
                    if (bt == null) {
                        showMsg("选择的必须是图片文件，请重新选择");
                        return;
                    }
                    bt.recycle();
                    if (isOperate) {
                        if (Choosemap.get(key) != null) {
                            ImagegridviewitemChoose.setVisibility(View.GONE);
                            Choosemap.remove(key);
                        } else {
                            if(BitmapCondense.isGif(key) && checkPictureLimit(key)){
                                showMsg("动态图片大小不能超过"+mLimitSize+"M");
                                return;
                            }
                            if (ImageCountMax <= Choosemap.size()) {
                                showMsg("最多可选择" + ImageCountMax + "张照片");
                                return;
                            }
                            ImagegridviewitemChoose.setVisibility(View.VISIBLE);
                            Choosemap.put(key, key);
                        }
                        updateBottomstyle();
                    } else {
                        if(checkPictureLimit(key)){
                            showMsg("图片大小超过限制，最多可选择"+mLimitSize+"M的图片");
                            return;
                        }
                        Intent intent = new Intent();
                        intent.putExtra("path", key);
                        setResult(RESCODE_BITMAPPATHS, intent);
                        finish();
                    }
                }
            };
            imageView.setOnClickListener(onClickListener);
            return arg1;
        }
    }

    LocalImageThread.ILocalImageAsyncTask asyncTask = new LocalImageThread.ILocalImageAsyncTask() {

        @Override
        public void UIUpdate(String path, Bitmap bitmap, ImageView imageView) {
            if (imageView != null && path.equals((String) imageView.getTag())) {
                imageView.setImageBitmap(bitmap);
            }
        }
    };

    public void updateBottomstyle() {
        if (Choosemap.size() == 0) {
            tv_choose_imagestandard.setTextColor(getResources().getColor(R.color.divider_color));
            tv_choose_trim.setTextColor(getResources().getColor(R.color.divider_color));
            btn_choose_preview.setBackgroundResource(R.drawable.fast_help_imtext);
            btn_choose_send.setBackgroundResource(R.drawable.fast_help_imtext);
            btn_choose_preview.setTextColor(getResources().getColor(R.color.divider_color));
            btn_choose_send.setTextColor(getResources().getColor(R.color.divider_color));
            btn_choose_send.setClickable(false);
        } else {
            tv_choose_imagestandard.setTextColor(getResources().getColor(R.color.text_res_zi_details));
            tv_choose_trim.setTextColor(getResources().getColor(R.color.text_res_zi_details));
            btn_choose_preview.setBackgroundResource(R.drawable.choose_btn_bg_selector1);
            btn_choose_send.setBackgroundResource(R.drawable.choose_btn_bg_selector2);
            btn_choose_send.setTextColor(getResources().getColorStateList(R.color.text_res_zi_details));
            btn_choose_preview.setTextColor(getResources().getColorStateList(R.color.text_res_zi_details));
            if (Choosemap.size() != 1) {
                tv_choose_trim.setTextColor(getResources().getColor(R.color.divider_color));
            }
            btn_choose_send.setClickable(true);
        }
    }

    class LoadingImage implements PhotoGridView.ILoadingImage {

        @Override
        public void loadingimag(int firstVisibleItem, int visibleItemCount) {
            adapter.firstVisibleItem = firstVisibleItem;
            adapter.visibleItemCount = visibleItemCount;
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (paths == null || paths.size() == 0) {
                return super.onKeyDown(keyCode, event);
            }
            Intent intent = new Intent(this, PhotoalbumActivity.class);
            Bundle bundle = new Bundle();
            bundle.putStringArrayList("paths", AllPath);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQCODE_PHOTOALBUM);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 判断给定路径的文件大小是否超过限制
     * @param path  true : 超过限制 ；false : 没有超过限制
     * @return
     */
    private boolean checkPictureLimit(String path){
        if(mLimitSize == -1 || TextUtils.isEmpty(path)){
            return false;
        }
        float fileSize = (float)new File(path).length() / 1024 / 1024;
        if(fileSize > mLimitSize){
            return true;
        }else{
            return false;
        }
    }

    // 压缩图片的线程
    class ImageCompressionThread extends Thread {
        List<String> paths;
        String putPath;

        public ImageCompressionThread(List<String> paths, String putPath) {
            this.paths = paths;
            this.putPath = putPath;
        }

        public ImageCompressionThread(Map<String, String> paths, String putPath) {
            this.putPath = putPath;
            this.paths = new ArrayList<String>();
            for (String key : paths.keySet()) {
                this.paths.add(paths.get(key));
            }
        }

        @Override
        public void run() {
            ArrayList<Pair<String, String>> toPahts = new ArrayList<Pair<String, String>>();
            //存放图片的文件夹
            File putPathFile = new File(putPath);
            //创建文件夹
            if (!putPathFile.exists()) 	putPathFile.mkdirs();
            Md5FileNameGenerator generator = new Md5FileNameGenerator();

            for (String path : paths) {
                //文件不存在则跳过
                if (!new File(path).exists()) continue;

                //first : 缩略图，second：原图
                Pair<String, String> pathPair = new Pair<>();

                try {
                    if (!BitmapCondense.isGif(path)) {//静态图片
                        //处理原图
                        String oriPicName = generator.generate(path);
                        String oriPicPath = putPath + "/" + oriPicName;
                        File oriFile = new File(oriPicPath);
                        if(!oriFile.exists()){
                            FileOutputStream oriStream = new FileOutputStream(oriFile);
                            //压缩原图大小
                            Bitmap oriBp = BitmapCondense.getAdaptiveBitmap(path, 1080, 1080);
                            //压缩原图质量
                            ByteArrayInputStream isBp = new ByteArrayInputStream(BitmapCondense.SavePicIn(oriBp, 200).toByteArray());
                            oriBp = BitmapFactory.decodeStream(isBp, null, null);
                            oriBp.compress(Bitmap.CompressFormat.JPEG, 100, oriStream);

                            oriBp.recycle();
                            oriBp = null;
                            isBp.close();
                            oriStream.close();
                        }
                        pathPair.setSecond(oriPicPath);


                        //是否需要缩略图
                        if(!isNeedTh){
                            pathPair.setFirst(null);
                            toPahts.add(pathPair);
                            continue;
                        }

                        //处理缩略图
                        String thPicName = oriPicName + "_th";
                        String thPicPath = putPath + "/" + thPicName;
                        File thFile = new File(thPicPath);
                        if(!thFile.exists()){
                            FileOutputStream thStream = new FileOutputStream(thFile);
                            //创建缩略图
                            int size[] = BitmapCondense.computThumSize(oriPicPath, 200);
                            Bitmap thBp = BitmapCondense.getAdaptiveBitmap(oriPicPath, size[0], size[1]);
                            thBp.compress(Bitmap.CompressFormat.JPEG, 100, thStream);

                            thBp.recycle();
                            thBp = null;
                            thStream.close();
                        }
                        pathPair.setFirst(thPicPath);
                        toPahts.add(pathPair);
                    } else {//动态图片
                        //将原图复制到缓存目录
                        String oriPicName = generator.generate(path);
                        String oriPicPath = putPath + "/" + oriPicName;
                        File oriFile = new File(oriPicPath);
                        if(!oriFile.exists()){
                            //将原gif文件复制一份
                            BitmapCondense.copy(oriPicPath, path);
                        }
                        pathPair.setSecond(oriPicPath);

                        //是否需要缩略图
                        if(!isNeedTh){
                            pathPair.setFirst(null);
                            toPahts.add(pathPair);
                            continue;
                        }

                        //处理缩略图
                        String thPicName = oriPicName + "_th";
                        String thPicPath = putPath + "/" + thPicName;
                        File thFile = new File(thPicPath);
//						if(!thFile.exists()){
                        FileOutputStream thStream = new FileOutputStream(thFile);
                        FileInputStream gifIs = new FileInputStream(path);
                        GifDecoder decoder = new GifDecoder();
                        decoder.setDecodeFrameListener(new GifDecoder.DecodeFrameListener() {
                            @Override
                            public void onDecodeFrame(int frameIndex, GifDecoder.GifFrame frame) {
                                Log.d(TAG, "frameIndex : "+frameIndex);
                            }
                        });
                        decoder.read(gifIs);

                        Log.d(TAG, "总帧数 : "+decoder.getFrames().size());

                        Bitmap firstFrame = decoder.getFrame(0);
                        //创建gif的缩略图
                        int[] size = BitmapCondense.computThumSize(new int[]{firstFrame.getWidth(), firstFrame.getHeight()}, 200);
                        Bitmap thPic = Bitmap.createScaledBitmap(firstFrame, size[0], size[1], true);
                        thPic.compress(Bitmap.CompressFormat.JPEG, 100, thStream);

                        firstFrame.recycle();
                        firstFrame = null;

                        gifIs.close();
                        thStream.close();
//						}
                        pathPair.setFirst(thPicPath);
                        toPahts.add(pathPair);
                    }
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            ResPahts = toPahts;
            Message message = handler.obtainMessage();
            message.what = MESSAGE_WHAT_SHENDIMAGE;
            handler.handleMessage(message);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MESSAGE_WHAT_SHENDIMAGE:
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    if(isNeedTh){
                        bundle.putSerializable("paths", ResPahts);
                    }else{
                        ArrayList<String> paths = new ArrayList<String>();
                        for(Pair<String, String> pair : ResPahts){
                            paths.add(pair.getSecond());
                        }
                        bundle.putStringArrayList("paths", paths);
                    }
                    intent.putExtras(bundle);
                    setResult(RESCODE_BITMAPPATHS, intent);
                    finish();
                    break;
                case MESSAGE_WHAT_ERROR:
                    showMsg("选择的必须是图片文件，请重新选择");
                    btn_choose_send.setClickable(true);
                    break;
            }
        }
    };
}
